// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { 
  Card, 
  Descriptions, 
  Tag, 
  Button, 
  message, 
  Spin, 
  Space, 
  Modal, 
  Transfer, 
  Typography,
  Divider,
  List,
  Avatar
} from 'antd';

// 3. 图标库
import { 
  ArrowLeftOutlined, 
  EditOutlined, 
  KeyOutlined, 
  TeamOutlined,
  UserOutlined,
  SaveOutlined
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 工具库
import { history, useParams } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { RoleDetail, PermissionList, UserRole, AssignPermissionRequest } from '@/services/generated/src/index';

const { Title, Text } = Typography;

interface TransferItem {
  key: string;
  title: string;
  description: string;
  disabled?: boolean;
}

const RoleDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(false);
  const [roleDetail, setRoleDetail] = useState<RoleDetail | null>(null);
  const [rolePermissions, setRolePermissions] = useState<PermissionList[]>([]);
  const [roleUsers, setRoleUsers] = useState<UserRole[]>([]);
  const [allPermissions, setAllPermissions] = useState<PermissionList[]>([]);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  const [transferLoading, setTransferLoading] = useState(false);

  // 加载角色详情
  const loadRoleDetail = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      await autoLoginInDev();
      
      const response = await apiClients.permissions.permissionsRolesRetrieve({ id: parseInt(id) });
      const responseData = (response as any).data || response;
      setRoleDetail(responseData);
    } catch (error) {
      message.error('加载角色详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载角色权限
  const loadRolePermissions = async () => {
    if (!id) return;
    
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsRolesPermissionsRetrieve({ id: parseInt(id) });
      const responseData = (response as any).data || response;
      setRolePermissions(responseData || []);
    } catch (error) {
      console.error('加载角色权限失败:', error);
    }
  };

  // 加载角色用户
  const loadRoleUsers = async () => {
    if (!id) return;
    
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsRolesUsersRetrieve({ id: parseInt(id) });
      const responseData = (response as any).data || response;
      setRoleUsers(responseData || []);
    } catch (error) {
      console.error('加载角色用户失败:', error);
    }
  };

  // 加载所有权限
  const loadAllPermissions = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsPermissionsList({
        page: 1,
        pageSize: 1000,
        isActive: true,
      });
      const responseData = (response as any).data || response;
      setAllPermissions(responseData?.items || []);
    } catch (error) {
      console.error('加载权限列表失败:', error);
    }
  };

  // 打开权限分配模态框
  const handleOpenPermissionModal = async () => {
    await loadAllPermissions();
    
    // 设置已选择的权限
    const currentPermissionIds = rolePermissions.map(p => p.id.toString());
    setTargetKeys(currentPermissionIds);
    setPermissionModalVisible(true);
  };

  // 保存权限分配
  const handleSavePermissions = async () => {
    if (!id) return;
    
    try {
      setTransferLoading(true);
      await autoLoginInDev();
      
      const request: AssignPermissionRequest = {
        role_id: parseInt(id),
        permission_ids: targetKeys.map(key => parseInt(key)),
      };
      
      await apiClients.permissions.permissionsRolesAssignPermissionsCreate({
        id: parseInt(id),
        assignPermissionRequest: request
      });
      
      message.success('权限分配成功');
      setPermissionModalVisible(false);
      loadRolePermissions();
      loadRoleDetail(); // 重新加载以更新权限数量
    } catch (error) {
      message.error('权限分配失败');
    } finally {
      setTransferLoading(false);
    }
  };

  // Transfer组件的数据源
  const transferDataSource: TransferItem[] = allPermissions.map(permission => ({
    key: permission.id.toString(),
    title: permission.display_name,
    description: `${permission.name} (${permission.module})`,
    disabled: permission.is_system,
  }));

  useEffect(() => {
    loadRoleDetail();
    loadRolePermissions();
    loadRoleUsers();
  }, [id]);

  if (loading) {
    return (
      <PageContainer>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
        </div>
      </PageContainer>
    );
  }

  if (!roleDetail) {
    return (
      <PageContainer>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Text type="secondary">角色不存在</Text>
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      header={{
        title: roleDetail.display_name,
        subTitle: roleDetail.name,
        extra: [
          <Button
            key="back"
            icon={<ArrowLeftOutlined />}
            onClick={() => history.back()}
          >
            返回
          </Button>,
          <Button
            key="edit"
            type="primary"
            icon={<EditOutlined />}
            disabled={roleDetail.is_system}
            onClick={() => history.push(`/permissions/roles?edit=${roleDetail.id}`)}
          >
            编辑角色
          </Button>,
        ],
      }}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* 基本信息 */}
        <Card title="基本信息">
          <Descriptions column={2}>
            <Descriptions.Item label="角色标识">{roleDetail.name}</Descriptions.Item>
            <Descriptions.Item label="显示名称">{roleDetail.display_name}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={roleDetail.is_active ? 'green' : 'red'}>
                {roleDetail.is_active ? '激活' : '禁用'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="类型">
              <Tag color={roleDetail.is_system ? 'orange' : 'blue'}>
                {roleDetail.is_system ? '系统角色' : '自定义角色'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="权限数量">
              <Tag color="blue" icon={<KeyOutlined />}>
                {roleDetail.permission_count}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="用户数量">
              <Tag color="purple" icon={<TeamOutlined />}>
                {roleDetail.user_count}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="创建者">{roleDetail.created_by_name || '-'}</Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {roleDetail.created_at ? new Date(roleDetail.created_at).toLocaleString() : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="描述" span={2}>
              {roleDetail.description || '-'}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 权限管理 */}
        <Card 
          title="权限管理" 
          extra={
            <Button
              type="primary"
              icon={<KeyOutlined />}
              disabled={roleDetail.is_system}
              onClick={handleOpenPermissionModal}
            >
              分配权限
            </Button>
          }
        >
          {rolePermissions.length > 0 ? (
            <List
              grid={{ gutter: 16, column: 3 }}
              dataSource={rolePermissions}
              renderItem={permission => (
                <List.Item>
                  <Card size="small">
                    <Space direction="vertical" size="small">
                      <Title level={5} style={{ margin: 0 }}>
                        {permission.display_name}
                      </Title>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        {permission.name}
                      </Text>
                      <Space>
                        <Tag color="blue">{permission.module}</Tag>
                        <Tag color="green">{permission.permission_type_display}</Tag>
                      </Space>
                    </Space>
                  </Card>
                </List.Item>
              )}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Text type="secondary">暂无权限</Text>
            </div>
          )}
        </Card>

        {/* 关联用户 */}
        <Card title="关联用户">
          {roleUsers.length > 0 ? (
            <List
              dataSource={roleUsers}
              renderItem={userRole => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar icon={<UserOutlined />} />}
                    title={userRole.user_name}
                    description={
                      <Space>
                        <Text type="secondary">
                          分配时间: {new Date(userRole.assigned_at).toLocaleString()}
                        </Text>
                        {userRole.expires_at && (
                          <Text type={userRole.is_expired ? 'danger' : 'secondary'}>
                            过期时间: {new Date(userRole.expires_at).toLocaleString()}
                          </Text>
                        )}
                      </Space>
                    }
                  />
                  <div>
                    <Tag color={userRole.is_active ? 'green' : 'red'}>
                      {userRole.is_active ? '激活' : '禁用'}
                    </Tag>
                    {userRole.is_expired && (
                      <Tag color="orange">已过期</Tag>
                    )}
                  </div>
                </List.Item>
              )}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Text type="secondary">暂无关联用户</Text>
            </div>
          )}
        </Card>
      </Space>

      {/* 权限分配模态框 */}
      <Modal
        title="分配权限"
        open={permissionModalVisible}
        onCancel={() => setPermissionModalVisible(false)}
        onOk={handleSavePermissions}
        confirmLoading={transferLoading}
        width={800}
        okText="保存"
        cancelText="取消"
        okButtonProps={{
          icon: <SaveOutlined />,
        }}
      >
        <Transfer
          dataSource={transferDataSource}
          targetKeys={targetKeys}
          onChange={setTargetKeys}
          render={item => `${item.title} - ${item.description}`}
          titles={['可用权限', '已分配权限']}
          showSearch
          filterOption={(inputValue, option) =>
            option.title.toLowerCase().includes(inputValue.toLowerCase()) ||
            option.description.toLowerCase().includes(inputValue.toLowerCase())
          }
          style={{ marginBottom: 16 }}
        />
      </Modal>
    </PageContainer>
  );
};

export default RoleDetailPage;
